/**
  * @description: 数据中台-权限管理-租户管理-新建/修改租户
  * @author: hj
  * @update: hj(2020-01-14)
  */
import React from 'react';
import IceContainer from '@icedesign/container';
import 'moment/locale/zh-cn';
import {Button, DatePicker, Input, Message} from '@alifd/next';
import {
    FormBinder as IceFormBinder,
    FormBinderWrapper as IceFormBinderWrapper,
    FormError as IceFormError,
} from '@icedesign/form-binder';
import styles from './index.module.scss';
import responsive from '@/request'
import $http from '@/service/Services';

const axios = $http;
const { TextArea } = Input;

let form;


/**
 * list
 */
class TenantAdd extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: {},
            id: "",
            parentId: null,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        this.formChange = this.formChange.bind(this);
        this.validateAllFormField = this.validateAllFormField.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get("id");
        const parentId = params.get("parentId");
        this.setState({
            id: id,
            parentId: parentId
        });
        if (id) {
            const that = this;
            axios.get(responsive.responsive.url + '/v1/org/getOrgEditById/' + id)
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data);
                    } else {
                        that.setState({
                            value: data.data
                        })
                    }
                })
                .catch(function (error) {
                    Message.error(error.message);
                })
        }
    };

    /* 表改变
    * @param formValue
    */
    formChange = (formValue) => {
        this.setState({
            value: formValue
        })
    };

    /**
     * 表验证
     */
    validateAllFormField = () => {
        let _this = this;
        form.validateAll((errors, values) => {
            if (errors) {
                Message.warning('请填写必要的数据.');
                return;
            }
            const that = this;
            if (typeof values["startDate"] === "object") {
                values["startDate"]=values["startDate"].format('YYYY-MM-DD') ;
            }
            
            if (typeof values["endDate"] === "object") {
                values["endDate"]=values["endDate"].format('YYYY-MM-DD') ;
            }
            
            if(!values.hasOwnProperty("id") || values["id"] === "") {
                values["parentId"] = _this.state.parentId;
            }

            axios.post(responsive.responsive.url + '/v1/org/saveOrUpdateOrg', values)
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data);
                    } else {
                        Message.success("操作成功.");
                        that.props.history.push("/aAuth/adminTenantList")
                    }
                })
                .catch(function (error) {
                    Message.error(error.message);
                })
        });
    };

    /**
     * 表
     * @returns {*}
     */
    render() {
        const _this = this;

        // 开始日期 < 结束日期
        const disabledStartDate = function (date, view) {
            if (_this.state.value.endDate) {
                let currentDate = _this.state.value.endDate;
                switch (view) {
                    case 'date':
                        return date.valueOf() > Date.parse(currentDate);
                    case 'year':
                        return date.year() > parseInt(currentDate.split('-')[0]);
                    case 'month':
                        return date.year() * 100 + date.month() > parseInt(currentDate.split('-')[0]) * 100 + parseInt(currentDate.split('-')[1]);
                    default: return false;
                }
            }
        };
        const disabledEndDate = function (date, view) {
            if (_this.state.value.startDate) {
                let currentDate = _this.state.value.startDate;
                switch (view) {
                    case 'date':
                        return date.valueOf() <= Date.parse(currentDate);
                    case 'year':
                        return date.year() < parseInt(currentDate.split('-')[0]);
                    case 'month':
                        return date.year() * 100 + date.month() < parseInt(currentDate.split('-')[0]) * 100 + parseInt(currentDate.split('-')[1]);
                    default: return false;
                }
            }
        };


        return (
            <div>
                <div className='container-header'>
                    <p style={{display: 'inline-block'}}>{this.state.id ? "修改租户" : "新建租户"}</p>
                    <Button type="normal" size="small" className='next-btn-normal table-btn-return' style={{float: 'right'}}>
                        <a onClick={() => {
                            this.props.history.go(-1)
                        }} > 返回</a>
                    </Button>
                </div>

                
                <IceContainer className='container-main'>
                    <IceFormBinderWrapper
                        value={this.state.value}
                        onChange={this.formChange}
                        ref={formRef => form = formRef}
                    >
                        <div className={styles.formContent}>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 编码：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message=" 租户编码不能为空"
                                    name="code"
                                >
                                    <Input maxLength={10}
                                           disabled={this.state.id != null && this.state.id != ''}
                                           placeholder="请输入编码名称"
                                           className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="code"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 租户名称：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message=" 租户名称不能为空"
                                    name="name"
                                >
                                    <Input maxLength={10}
                                        placeholder="请输入租户名称"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="name"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 服务有效期：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message="开始时间不能为空"
                                    name="startDate"
                                >
                                   <DatePicker disabledDate={disabledStartDate} style={{marginRight:"10px"}} format="YYYY-MM-DD" name="startDate"/>
                                </IceFormBinder>
                                —
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message=" 结束时间不能为空"
                                    name="endDate"
                                >
                                   <DatePicker disabledDate={disabledEndDate} style={{marginLeft:"10px"}} format="YYYY-MM-DD" name="endDate"/>
                                </IceFormBinder>

                                <div className={styles.formError}>
                                    <IceFormError name="startDate"/>
                                    <IceFormError name="endDate"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 描述：</div>
                                <IceFormBinder
                                    triggerType="onBlur"
                                    name="description"
                                >
                                    <TextArea rows={4}
                                              maxLength={50}
                                           placeholder="请输入描述"
                                           className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="description"/>
                                </div>
                            </div>
                            <Button
                                type="primary"
                                className='pipe-btn-submit'
                                onClick={this.validateAllFormField}
                            >
                                提 交
                            </Button>
                        </div>
                    </IceFormBinderWrapper>
                </IceContainer>
            </div>
        );
    }

}

export default TenantAdd;
